/**
 *  Copyright [2011] Steffen Kämpke
 *  mailto: steffen.kaempke@t-online.de
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pennychecker.swing.presenter.ext.component;

import com.pennychecker.swing.presenter.ext.event.HasHandlers;
import com.pennychecker.swing.mvp.event.EventHandler;
import com.pennychecker.swing.mvp.event.HandlerManager;
import com.pennychecker.swing.mvp.event.HandlerRegistration;
import com.pennychecker.swing.mvp.event.MvpEvent;
import com.pennychecker.swing.mvp.event.MvpEvent.Type;

/**
 *
 * @author Steffen Kämpke mailto:steffen.kaempke@t-online.de
 */
public class HandlerAdapter implements HasHandlers {

    private HandlerManager handlerManager;

    /**
     *
     */
    public HandlerAdapter() {
    }

    @Override
    public void fireEvent(MvpEvent<?> event) {
        if (handlerManager != null) {
            handlerManager.fireEvent(event);
        }
    }

    /**
     * Adds this handler to the jcomponent.
     *
     * @param <H> the type of handler to add
     * @param type the event type
     * @param handler the handler
     * @return {@link HandlerRegistration} used to remove the handler
     */
    public final <H extends EventHandler> HandlerRegistration addHandler(
            H handler, final MvpEvent.Type<H> type) {
        final HandlerManager handlerMan = ensureHandlers();
        final HandlerRegistration handlerRegistration = handlerMan.addHandler(type, handler);
        return handlerRegistration;
    }

    /**
     * Gets the number of handlers listening to the event type.
     *
     * @param type the event type
     * @return the number of registered handlers
     */
    protected int getHandlerCount(Type<?> type) {
        return handlerManager == null ? 0 : handlerManager.getHandlerCount(type);
    }

    /**
     * Ensures the existence of the handler manager.
     *
     * @return the handler manager
     * */
    HandlerManager ensureHandlers() {
        return handlerManager == null ? handlerManager = new HandlerManager(this)
                : handlerManager;
    }

    HandlerManager getHandlerManager() {
        return handlerManager;
    }
}
